package com.jian.socks5.tcp.handler;

import com.jian.socks5.common.Constants;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/****
 * 客户端转发到目标端
 */
@ChannelHandler.Sharable
public
class Client2ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel ctxChannel = ctx.channel();
        Channel channel = ctxChannel.attr(Constants.CLIENT_CHANNEL_ATTR).get();
        String ipAndPort = ctxChannel.attr(Constants.CHANNEL_ATTR_IPINFO).get();
        if (channel != null) {
            //关闭连接的目标机器
            channel.close();
        }
        //关闭异常连接
        ctx.close();
        System.err.println("Client2ServerHandler异常，已关闭目标连接和客户端连接！IP:" + ipAndPort + "__" + cause.getMessage());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel().attr(Constants.CLIENT_CHANNEL_ATTR).get();
        if (channel != null) {
            channel.writeAndFlush(msg);
        }
        //ctx.writeAndFlush(msg);
    }
}